import axios from 'axios'
import { getAjaxurl, getLinkToUrl, devProTest } from './OperatesCookie.js'

//------------获取后台数据-------------
// 创建axios实例
export function dataAxios(config) {
  const instance = axios.create({
    baseURL: getAjaxurl(),
  })
  instance.defaults.withCredentials = true

  instance.interceptors.request.use((response) => {
    let token = window.localStorage.getItem('refreshToken')
    if (token) {
      response.headers.refreshToken = token
    } else {
      window.location.href = getLinkToUrl('iCanLogin')
    }
    let authToken = window.localStorage.getItem('authToken')
    if (authToken) {
      response.headers.authToken = authToken
    }
    let EmpNo = localStorage.getItem('empNo')

    return response
  })
  // 发送真正的网络请求
  return instance
    .request(config)
    .then()
    .catch((error) => checkStatus(error.response, instance))
}

let isRefreshing = true
function checkStatus(response, instance) {
  console.log('response:', response, isRefreshing)
  if (response && response.status === 401) {
    window.localStorage.removeItem('refreshToken')
    window.location.href = getLinkToUrl('iCanLogin')
  } else if (response && response.status === 403) {
    // 刷新token的函数,这需要添加一个开关，防止重复请求
    window.localStorage.removeItem('authToken')
    if (isRefreshing) {
      let EmpNo = localStorage.getItem('empNo')
      if (EmpNo) {
        refreshTokenRequst(EmpNo)
      } else {
        window.localStorage.removeItem('refreshToken')
        window.location.href = getLinkToUrl('iCanLogin')
      }
    }
    isRefreshing = false
    // 将当前的请求保存在观察者数组中
    const retryOriginalRequest = new Promise((resolve) => {
      addSubscriber(() => {
        resolve(instance.request(response.config))
      })
    })
    return retryOriginalRequest
  } else {
    return response
  }
}
function refreshTokenRequst(EmpNo) {
  let data
  dataAxios({
    url: '/auth/getToken',
    params: { empNo: EmpNo },
  }).then(function(responses) {
    if (responses.status === 200) {
      if (responses.data.code === 200 && responses.data.message == 'OK') {
        localStorage.setItem('authToken', responses.data.data)
        // 并且将所有存储到观察者数组中的请求重新执行。
        onAccessTokenFetched()
        // 纸条撕掉
        isRefreshing = true
      }
    }
  })
}
// 观察者
let subscribers = []
function onAccessTokenFetched() {
  subscribers.forEach((callback) => {
    callback()
  })
  subscribers = []
}

function addSubscriber(callback) {
  subscribers.push(callback)
}
